import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from fastapi.testclient import TestClient
from app.main import app
from app.models import Base, get_db
import os

# 使用内存数据库进行测试
SQLALCHEMY_DATABASE_URL = "sqlite:///:memory:"

engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


def override_get_db():
    try:
        db = TestingSessionLocal()
        yield db
    finally:
        db.close()


@pytest.fixture(scope="function")
def client():
    # Ensure all models are imported
    from app.models import User, Exam, Question, Answer, Score, Log
    
    # Create tables
    Base.metadata.create_all(bind=engine)
    
    # Override dependency
    app.dependency_overrides[get_db] = override_get_db
    
    with TestClient(app) as test_client:
        yield test_client
    
    # Clean up
    Base.metadata.drop_all(bind=engine)
    app.dependency_overrides.clear()


@pytest.fixture(scope="function")
def db_session():
    Base.metadata.create_all(bind=engine)
    db = TestingSessionLocal()
    try:
        yield db
    finally:
        db.close()
        Base.metadata.drop_all(bind=engine)


@pytest.fixture
def auth_headers(client):
    # 创建测试用户
    user_data = {
        "username": "testuser",
        "email": "test@example.com",
        "full_name": "Test User",
        "password": "testpassword123",
        "role": "student"
    }
    
    # 注册用户
    client.post("/api/auth/register", json=user_data)
    
    # 登录获取token
    login_data = {
        "username": "testuser",
        "password": "testpassword123"
    }
    
    response = client.post("/api/auth/login", json=login_data)
    token = response.json()["access_token"]
    
    return {"Authorization": f"Bearer {token}"}


@pytest.fixture
def admin_auth_headers(client):
    # 创建管理员用户
    admin_data = {
        "username": "admin",
        "email": "admin@example.com",
        "full_name": "Admin User",
        "password": "adminpassword123",
        "role": "admin"
    }
    
    # 注册管理员
    client.post("/api/auth/register", json=admin_data)
    
    # 登录获取token
    login_data = {
        "username": "admin",
        "password": "adminpassword123"
    }
    
    response = client.post("/api/auth/login", json=login_data)
    token = response.json()["access_token"]
    
    return {"Authorization": f"Bearer {token}"}


@pytest.fixture
def teacher_auth_headers(client):
    # 创建教师用户
    teacher_data = {
        "username": "teacher",
        "email": "teacher@example.com",
        "full_name": "Teacher User",
        "password": "teacherpassword123",
        "role": "teacher"
    }
    
    # 注册教师
    client.post("/api/auth/register", json=teacher_data)
    
    # 登录获取token
    login_data = {
        "username": "teacher",
        "password": "teacherpassword123"
    }
    
    response = client.post("/api/auth/login", json=login_data)
    token = response.json()["access_token"]
    
    return {"Authorization": f"Bearer {token}"}


@pytest.fixture
def create_test_exam(client, teacher_auth_headers):
    exam_data = {
        "title": "Test Exam",
        "description": "A test exam for testing",
        "duration": 60,
        "total_score": 100,
        "pass_score": 60,
        "start_time": "2024-01-01T09:00:00",
        "end_time": "2024-01-01T11:00:00",
        "exam_type": "formal",
        "is_shuffle": True,
        "allow_review": True
    }
    
    response = client.post("/api/exams/", json=exam_data, headers=teacher_auth_headers)
    return response.json()


@pytest.fixture
def create_test_question(client, create_test_exam, teacher_auth_headers):
    question_data = {
        "exam_id": create_test_exam["id"],
        "question_type": "single_choice",
        "title": "Test Question",
        "content": "What is 2+2?",
        "options": [{"label": "A", "text": "4"}, {"label": "B", "text": "3"}],
        "correct_answer": "A",
        "score": 5.0,
        "difficulty": 1
    }
    
    response = client.post("/api/questions/", json=question_data, headers=teacher_auth_headers)
    return response.json()